package com.woniuxy.hrp.security;

import com.woniuxy.hrp.entity.Admin;
import com.woniuxy.hrp.entity.Doctor;
import com.woniuxy.hrp.entity.Patient;
import com.woniuxy.hrp.entity.Perm;
import com.woniuxy.hrp.mapper.AdminMapper;
import com.woniuxy.hrp.mapper.DoctorMapper;
import com.woniuxy.hrp.mapper.PatientMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 用于替代SpringSecurity中的UserDetailsService,使得与前端比对的是数据库查出的账号密码而不是默认的
 */

@Component
public class HrpUserDetailsService implements UserDetailsService {
    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库查出信息，放到SpringSecurity提供的User类中。该User类中的权限集合(集合的类型也要按规定给)不能为空
        User user =null;
        Patient patient1 = patientMapper.getByAccount(username);
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        int account=0;
        if(patient1!=null){
            account++;
            user = new HrpUser(patient1.getId(),patient1.getAccount(),patient1.getPassword(),1,list);
        }
        Doctor doctor = doctorMapper.getByAccount(username);
        if(doctor!=null){
            account++;
            Doctor doctor1 = doctorMapper.selectByDoctorId(doctor.getId());
            List<Perm> perms = doctor1.getPerms();
            for(Perm perm:perms){
                list.add(new SimpleGrantedAuthority(perm.getCode()));
            }
            user = new HrpUser(doctor.getId(),doctor.getAccount(),doctor.getPassword(),2,list);
        }
        Admin admin = adminMapper.getByAccount(username);
        if(admin!=null){
            account++;
            user = new HrpUser(admin.getId(),admin.getAccount(),admin.getPassword(),3,list);
        }
        if(account==0){
            throw new UsernameNotFoundException("账号不存在");
        }

//        SpringSecurity提供的User

        return user;
    }
}
